<template>
    <sub-box>
        <breadcrumb :title="'修改自建系统'" class="mb20">
            <el-button type="primary" size="small mr10" @click="upData">保存</el-button>
        </breadcrumb>
        <div v-loading="loading">
            <div class="built-info white-block">
                <div class="head-line">自建系统信息</div>
                <el-form class="form-common" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px">
                    <el-form-item label="自建系统名称" prop="name">
                        <el-input v-model="ruleForm.name" size="small"></el-input>
                    </el-form-item>
                    <el-form-item label="自建系统代码">
                        <el-link type="primary" :underline="false">自动获取</el-link>
                    </el-form-item>
                    <el-form-item label="自建系统描述" prop="remark">
                        <el-input v-model="ruleForm.remark" type="textarea" size="small"
                                  :autosize="{ minRows: 4, maxRows: 4}"></el-input>
                    </el-form-item>
                </el-form>
            </div>

            <div class="built-address white-block">
                <div class="head-line">
                    <div class="info">IP内容有修改后，当前IP无法进行修改和删除操作</div>
                    服务地址
                </div>
                <table-list :data="ipList" :tableColumn="header" :slotColumns="slotColumns" ref="table">
                    <template slot="code" slot-scope="scope">
                        <span>{{scope.$index+1}}</span>
                    </template>
                    <template slot="ip" slot-scope="scope">
                        <el-input v-model="scope.row.ip" placeholder="" :disabled="scope.row.state>0" size="small"
                                  style="width: 80%"></el-input>
                    </template>
                    <template slot="service" slot-scope="scope">
                        <el-link type="primary" :underline="false" @click="managerApps(scope.row)"
                                 :disabled="scope.row.state==2">管理绑定资源
                        </el-link>
                    </template>
                    <template slot="operate" slot-scope="scope">
                        <el-link type="primary" icon="el-icon-delete" :underline="false" @click="remove(scope)"
                                 v-if="(scope.row.state||0)<1">
                            删除
                        </el-link>
                    </template>
                </table-list>
                <el-button class="small mt20" size="small" type="primary" @click="addIp">添加</el-button>
            </div>
        </div>
        <dialog-box :show.sync="show" :toBody="false" :title="'绑定服务'" :width="'900px'" @save="save">
            <div class="has-serve">
                <p class="line">已绑定服务</p>
                <ul>
                    <li v-for="(list,index) in serveData" :key="index">
                        <span class="ellipsis">{{list.resName}}</span><i class="iconfont el-icon-close"
                                                                         @click="removeApp(list,index)"></i>
                    </li>
                </ul>
            </div>
            <div class="could-serve">
                <p class="line">可关联服务列表</p>
                <table-list :data="tableData" :selection="true" :tableColumn="header1" :slotColumns="slotColumns1"
                            @selectionChange="selectionChange" ref="table1">
                    <template slot="resName" slot-scope="scope">
                        <div class="ellipsis">{{scope.row.resName}}</div>
                    </template>
                    <template slot="state" slot-scope="scope">
                        <div class="ellipsis" v-if="scope.row.state==0">未关联</div>
                        <div class="ellipsis" v-else-if="scope.row.state==1">已关联</div>
                        <div class="ellipsis" v-else>审核中</div>
                    </template>
                </table-list>
                <div class="mt20">
                    <page :data="pageData" v-if="pageData" class="page" @jumpPage="getList"></page>
                    <el-checkbox v-model="checked" @change="change">全选</el-checkbox>
                    <el-button type="primary" size="small" class="relate" @click="relate">关联</el-button>
                </div>
            </div>
        </dialog-box>
    </sub-box>
</template>

<script>
    import breadcrumb from '../../components/breadcrumb'
    import subBox from '../../components/layout/layout-sub'
    import tableList from '../../components/table'
    import dialogBox from '../../components/dialog'
    import page from '../../components/pagination'

    export default {
        name: '',
        data() {
            return {
                ruleForm: {
                    name: '',
                    remark: ''
                },
                rules: {
                    name: [
                        {required: true, message: '请输入名称', trigger: 'blur'}
                    ]
                },
                tableData: [],
                serveData: [],
                header1: [
                    {
                        prop: 'resName',
                        label: '服务名称',
                        minWidth: '70%',
                        align: 'center'
                    },
                    {
                        prop: 'state',
                        label: '状态',
                        minWidth: '30%',
                        align: 'center'
                    }
                ],
                ipList: [],
                header: [
                    {
                        prop: 'code',
                        label: '编号',
                        minWidth: '25%',
                        align: 'center'
                    },
                    {
                        prop: 'ip',
                        label: 'IP',
                        minWidth: '25%',
                        align: 'center'
                    },
                    {
                        prop: 'service',
                        label: '绑定服务',
                        minWidth: '25%',
                        align: 'center'
                    },
                    {
                        prop: 'operate',
                        label: '操作',
                        minWidth: '25%',
                        align: 'center'
                    }
                ],
                slotColumns: ['code', 'ip', 'operate', 'service'],
                slotColumns1: ['resName', 'state'],
                show: false,
                pageData: {},
                loading: false,
                id: '',
                delIdList: [], // 被删除的有id的ip集
                checked: false,
                selection: null,
                currentIp: null,
                index: 1,
                pattern: /^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$/
            }
        },
        mounted() {
            this.id = this.$route.params.id
            this.getDetail()
        },
        methods: {
            managerApps(obj) {
                this.currentIp = obj
                if (this.pattern.test(obj.ip)) { // IP校验
                    this.serveData = []
                    this.getList()
                } else {
                    this.$alert(obj.ip ? 'ip：' + obj.ip + '格式错误' : 'ip不能为空', '提示', {
                        confirmButtonText: '确定',
                        closeOnClickModal: true,
                        callback: action => {
                        },
                        closeOnPressEscape: true
                    })
                }
            },
            // 绑定服务弹窗确定方法
            save() {
                let resIdList = []
                this.serveData.forEach(item => {
                    resIdList.push(item.resId)
                })
                this.currentIp.resIdList = resIdList.join(',')
                this.show = false
            },
            change() {
                if (this.checked) {
                    this.$refs.table1.handleSelectionAll()
                } else {
                    this.$refs.table1.handleSelectionClear()
                }
            },
            selectionChange(val) {
                this.selection = val
                let list = this.tableData.filter(el => !el.disabled)
                if (val.length === list.length) {
                    this.checked = true
                } else {
                    this.checked = false
                }
            },
            relate() {
                // 将所有选中项标记为已关联
                this.selection.forEach(item => {
                    item.state = 1
                })
                // 处理serveData，将其先与selection相同部分去除得到list，再赋值list+selection
                if (this.selection[0]) {
                    let list = this.serveData.filter(el => {
                        let exist = false
                        for (let i = 0; i < this.selection.length; i++) {
                            if (this.selection[i].id === el.id) {
                                exist = true
                            }
                        }
                        if (!exist) return el
                    })
                    this.serveData = [...this.selection, ...list]
                }
            },
            getDetail() {
                this.loading = true
                this.$http.get('/deptAdmin/getAppInfoById', {
                    id: this.id
                }).then(result => {
                    this.loading = false
                    if (result.success) {
                        this.ruleForm.name = result.data.sysName
                        this.ruleForm.remark = result.data.sysDescribe
                        this.ipList = result.data.ipList
                    }
                }).catch(() => {
                    this.loading = false
                })
            },
            validate(formName, callback) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if (callback) callback()
                    } else {
                        return false
                    }
                })
            },
            upData() {
                let _this = this
                this.validate('ruleForm', () => {
                    let num = 0, errorIp = null
                    for (let i = 0; i < this.ipList.length; i++) {
                        if (!_this.pattern.test(_this.ipList[i].ip) && num < 1) {
                            errorIp = _this.ipList[i]
                            num++
                        }
                    }
                    if (num < 1) {
                        this.loading = true
                        this.$http.post('/deptAdmin/updateApp', {
                            id: this.id, // 主键
                            def: 0,
                            sysDescribe: this.ruleForm.remark,
                            sysName: this.ruleForm.name,
                            sysState: 0,
                            ipList: this.ipList,
                            userId: 0,
                            delIdList: this.delIdList
                        }).then(result => {
                            this.loading = false
                            if (result.success) {
                                this.$emit('upload')
                                this.$nextTick(() => {
                                    this.$method.historyBack()
                                })
                            }
                        }).catch(() => {
                            this.loading = false
                        })
                    } else {
                        this.$alert(errorIp.ip ? 'ip：' + errorIp.ip + '格式错误' : 'ip不能为空', '提示', {
                            confirmButtonText: '确定',
                            closeOnClickModal: true,
                            callback: action => {
                            },
                            closeOnPressEscape: true
                        })
                    }
                })
            },
            addIp() {
                this.ipList.push({
                    resIdList: null,
                    relfSysId: 0,
                    id: null,
                    ip: '',
                    state: 0
                })
            },
            remove(scope) {
                this.ipList.splice(scope.$index, 1)
                if (scope.row.id && this.delIdList.indexOf(scope.row.id) < 0) this.delIdList.push(scope.row.id)
            },
            removeApp(list, index) {
                this.tableData.map(x => {
                    if (x.resId === list.resId) x.state = 0
                    return x
                })
                this.serveData.splice(index, 1)
            },
            getList(index) {
                this.loading = true
                if (index) this.index = index
                this.$http.get('/rdResManagement/getUserIpBingResList', {
                    ipId: this.currentIp.id,
                    current: this.index || 1,
                    size: 10
                }).then(result => {
                    this.loading = false
                    if (result.success) {
                        let list = result.data.records, list1 = [], list2 = []
                        // 元数据处理：标记disabled、checked
                        if (list && list[0]) {
                            list.map(x => {
                                if (x.state === 2) {
                                    x.disabled = true
                                } else {
                                    x.disabled = false
                                    for (let i = 0; i < this.serveData.length; i++) {
                                        if (this.serveData[i].resId === x.resId) {
                                            x.state = 1
                                        }
                                    }
                                    if (x.state === 1) {
                                        x.checked = true
                                    }
                                }
                                return x
                            })
                        }
                        this.tableData = list
                        // list1 元数据中所有已关联项
                        list1 = list.filter(x => x.checked)
                        // 处理serveData，将其先与list1相同部分去除得到list2，再赋值list2+list1
                        if (list1[0]) {
                            list2 = this.serveData.filter(el => {
                                let exist = false
                                for (let i = 0; i < list1.length; i++) {
                                    if (list1[i].resId === el.resId) {
                                        exist = true
                                    }
                                }
                                if (!exist) return el
                            })
                            this.serveData = [...list2, ...list1]
                        }
                        // 分页数据
                        this.pageData = result.data
                        delete this.pageData['records']
                        this.show = true
                        // 延迟将勾选项与全选标记重置
                        this.$nextTick(() => {
                            this.selection = null
                            this.checked = false
                        })
                    }
                }).catch(() => {
                    this.loading = false
                })
            }
        },
        components: {
            breadcrumb,
            subBox,
            tableList,
            dialogBox,
            page
        }
    }
</script>

<style scoped lang="less">
    .built-info {
        .line {
            margin-bottom: 20px;

            > * {
                display: inline-block;
                max-width: 900px;
            }

            label {
                float: left;
                width: 150px;
                text-align: right;
                margin-right: 15px;
                line-height: 40px;
                font-size: 16px;
            }

            .el-link {
                line-height: 40px;
            }
        }
    }

    .built-address {
        margin-top: 30px;
    }

    .el-checkbox {
        padding-left: 14px;

        .el-checkbox__label {
            fnt-size: 16px;
        }
    }

    .page {
        float: right;
    }

    .relate {
        margin-left: 10px;
    }

    .has-serve, .could-serve {
        .line {
            color: #999;
            line-height: 40px;
        }
    }

    .has-serve {
        li {
            display: inline-block;
            width: 48%;
            margin-right: 3%;
            border: 1px solid #EFEFEF;
            padding: 5px 10px;
            margin-bottom: 8px;
            line-height: 20px;
            text-align: right;

            &:nth-of-type(2n) {
                margin-right: 0;
            }

            span {
                float: left;
                max-width: 90%;
            }

            .el-icon-close {
                cursor: pointer;
            }
        }
    }

    .form-common {
        max-width: 1000px;
    }
</style>
